package com.asiainfo.dacp.datastash.open.controller;

import com.asiainfo.dacp.datastash.domain.stepdefine.models.DataStashStepDefine;
import com.asiainfo.dacp.datastash.domain.stepdefine.repos.DataStashStepDefineRepository;
import com.asiainfo.dacp.datastash.domain.stepdefine.service.DataStashStepDefineService;
import com.asiainfo.dacp.jdbc.JdbcTemplate;
import com.asiainfo.dacp.util.JsonHelper;

import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by winter on 2017/10/31.
 */
@RestController
@RequestMapping("/open/datastash")
@Api(tags={"datastash"},value="节点定义")
public class DataStashStepDefineController {

    @Autowired
    DataStashStepDefineRepository dataStashStepDefineRepo;

    @Autowired
    DataStashStepDefineService stepDefineService;

    @RequestMapping(value = "stepdefines", method = RequestMethod.GET)
    @ApiOperation(tags = {"stepdefine"}, value = "查询所有节点定义")
    public @ResponseBody
    List<DataStashStepDefine> stepdefines(HttpServletRequest request, Model model)throws Exception {
        return stepDefineService.findAll();
    }

    @RequestMapping(value = "stepdefine/all", method = RequestMethod.GET)
    @ApiOperation(tags = {"stepdefine"}, value = "分页查询所有节点定义")
    public @ResponseBody
    Page<DataStashStepDefine> stepdefines(Model model, HttpServletRequest request,
                                          @RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                          @RequestParam(value = "stepInstLabel", defaultValue = "all") String stepInstLabel,
                                          @RequestParam(value = "stepType", defaultValue = "all") String stepType,
                                          @RequestParam(value = "groupType", defaultValue = "all") String groupType,
                                          @RequestParam(value = "stepState", defaultValue = "all") String stepState,
                                          @RequestParam(value = "stepStyle", defaultValue = "all") String stepStyle,
                                          @RequestParam(value = "sortColumn", defaultValue = "stepSeq")  String sortColumn,
                                          @RequestParam(value = "desc", defaultValue = "asc")  String desc )throws Exception {
        return dataStashStepDefineRepo.findAll(pageNum,pageSize,stepInstLabel,stepType,groupType,stepState,stepStyle,sortColumn,desc);
    }

    @RequestMapping(value = "stepDefine/creator", method = RequestMethod.POST)
    @ApiOperation(tags = {"stepDefine"}, value = "创建单元节点定义")
    public DataStashStepDefine stepDefineCreator(@RequestBody String body, HttpServletRequest request, Model model, HttpServletResponse resp)
            throws  Exception {
        DataStashStepDefine stepDefine =null;
        try{
            stepDefine = new Gson().fromJson(body,DataStashStepDefine.class);
        }catch(RuntimeException e){
            e.printStackTrace();
            throw e;
        }
        return dataStashStepDefineRepo.save(stepDefine);
    }


    @RequestMapping(value = "stepdefine/{id}", method = RequestMethod.GET)
    @ApiOperation(tags = {"stepdefine"}, value = "查询单元节点定义")
    public DataStashStepDefine stepDefineQuery( @PathVariable String id, HttpServletRequest request, Model model, HttpServletResponse resp)
            throws  Exception {
        return dataStashStepDefineRepo.findOne(id);
    }

    @RequestMapping(value = "stepdefine/{id}/delete", method = RequestMethod.POST)
    @ApiOperation(tags = {"stepdefine"}, value = "删除单元节点定义")
    public Map stepDefineDelete(@PathVariable String id, HttpServletRequest request, Model model, HttpServletResponse resp)
            throws  Exception {
        String responseBody = null;
        Map responseMessage = new HashMap();
        responseMessage.put("success", true);
        try {
            dataStashStepDefineRepo.deleteEntity(id);
        } catch (Exception e) {
            e.printStackTrace();
            responseBody = "操作失败！"+e.getMessage();
            responseMessage.put("msg", responseBody);
            responseMessage.put("success", false);
        }
        return responseMessage;
    }
    
    @RequestMapping(value="stepforms",method=RequestMethod.GET)
	public @ResponseBody Object lang(HttpServletRequest request){
        return mergeJson(WebApplicationContextUtils.findWebApplicationContext(request.getServletContext()));
	}

	private Map<String,Object> mergeJson(WebApplicationContext ctx){
        Map<String,Object> tmpObj = new HashMap<>();
        try {
            Resource[] resources =  ctx.getResources("classpath*:dacp-view/datastash/workshop/unit_creator/json/**/**.json");

            for (org.springframework.core.io.Resource resource : resources) {
                if (resource != null && resource.isReadable()) {
                    try {
                        StringWriter sw = new StringWriter();
                        IOUtils.copy(resource.getInputStream(),sw,Charset.forName("utf-8"));
                        tmpObj.putAll(JsonHelper.getInstance().read(sw.toString().intern(),Map.class));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        handle(tmpObj);
        return tmpObj;
    }
	public void handle(Map<String, Object> map) {
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while(iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            if(next.getValue() instanceof Map) {
                handle((Map<String, Object>) next.getValue());
            }
            if(next.getValue() instanceof List) {
                Iterator iterator1 = ((List) next.getValue()).iterator();
                while(iterator1.hasNext()) {
                    Object val = iterator1.next();
                    if(val instanceof Map) {
                        handle((Map<String, Object>) val);
                    }
                }
            }
            if("storeSql".equals(next.getKey())) {
                JdbcTemplate jt = new JdbcTemplate();
                List<Map<String, Object>> rs = jt.queryForList(next.getValue().toString());
                map.put("options", rs);
            }
        }
    }
}
